{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 导入cv2等库 读入图片"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-11T00:07:33.461343Z",
     "start_time": "2018-05-11T00:07:31.956093Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "from sklearn import svm, preprocessing\n",
    "from skimage import feature as ft"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-11T00:07:44.218617Z",
     "start_time": "2018-05-11T00:07:35.428838Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "training_set = []\n",
    "for i in range(1, 401):\n",
    "    training_set.append(cv2.imread('test8/%06d.png' % i))\n",
    "for i in range(502, 902):\n",
    "    training_set.append(cv2.imread('test8/%06d.png' % i))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-10T08:22:12.524726Z",
     "start_time": "2018-05-10T08:22:12.522316Z"
    }
   },
   "outputs": [],
   "source": [
    "training_label = np.array([1 if i < 400 else 0 for i in range(800)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-10T08:22:36.376277Z",
     "start_time": "2018-05-10T08:22:34.215499Z"
    }
   },
   "outputs": [],
   "source": [
    "test_set = []\n",
    "for i in range(401, 502):\n",
    "    test_set.append(cv2.imread('test8/%06d.png' % i))\n",
    "for i in range(902, 1001):\n",
    "    test_set.append(cv2.imread('test8/%06d.png' % i))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 计算HOG特征向量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-10T08:22:49.916800Z",
     "start_time": "2018-05-10T08:22:39.255203Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/song/anaconda3/lib/python3.6/site-packages/skimage/feature/_hog.py:119: skimage_deprecation: Default value of `block_norm`==`L1` is deprecated and will be changed to `L2-Hys` in v0.15\n",
      "  'be changed to `L2-Hys` in v0.15', skimage_deprecation)\n"
     ]
    }
   ],
   "source": [
    "training_set_hog = [ft.hog(cv2.resize(cv2.cvtColor(i, cv2.COLOR_BGR2GRAY), (224, 224))) for i in training_set]\n",
    "training_set_hog_nparray = np.vstack(training_set_hog)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-10T08:24:35.629201Z",
     "start_time": "2018-05-10T08:24:33.020614Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/song/anaconda3/lib/python3.6/site-packages/skimage/feature/_hog.py:119: skimage_deprecation: Default value of `block_norm`==`L1` is deprecated and will be changed to `L2-Hys` in v0.15\n",
      "  'be changed to `L2-Hys` in v0.15', skimage_deprecation)\n"
     ]
    }
   ],
   "source": [
    "test_set_hog = [ft.hog(cv2.resize(cv2.cvtColor(i, cv2.COLOR_BGR2GRAY), (224, 224))) for i in test_set]\n",
    "test_set_hog_nparray = np.vstack(test_set_hog)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 训练svm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-10T08:22:56.592082Z",
     "start_time": "2018-05-10T08:22:56.589411Z"
    }
   },
   "outputs": [],
   "source": [
    "clf_hog = svm.SVC()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-10T08:23:33.130969Z",
     "start_time": "2018-05-10T08:22:58.230140Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,\n",
       "  decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf',\n",
       "  max_iter=-1, probability=False, random_state=None, shrinking=True,\n",
       "  tol=0.001, verbose=False)"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "clf_hog.fit(training_set_hog_nparray, training_label)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-10T08:24:49.479238Z",
     "start_time": "2018-05-10T08:24:39.499582Z"
    }
   },
   "outputs": [],
   "source": [
    "test_predict_label_hog = clf_hog.predict(test_set_hog_nparray)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T14:28:07.693169Z",
     "start_time": "2018-05-07T14:28:07.601128Z"
    }
   },
   "outputs": [],
   "source": [
    "test_predict_label_hog_positive = test_predict_label_hog[:100]\n",
    "test_predict_label_hog_negative = test_predict_label_hog[100:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T11:33:54.493697Z",
     "start_time": "2018-05-07T11:32:35.917804Z"
    }
   },
   "outputs": [],
   "source": [
    "training_predict_label_hog = clf_hog.predict(training_set_hog_nparray)\n",
    "training_predict_label_hog_positive = training_predict_label_hog[:400]\n",
    "training_predict_label_hog_negative = training_predict_label_hog[400:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T11:41:25.850815Z",
     "start_time": "2018-05-07T11:41:25.839410Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "HOG+SVM Training Set Confusion Matrix\n",
      "          Ture      False\n",
      "Positive： 386        14\n",
      "Negative： 236        164\n",
      "检测率: 0.965, 虚警率: 0.41\n"
     ]
    }
   ],
   "source": [
    "print('HOG+SVM Training Set Confusion Matrix\\n          Ture      False')\n",
    "\n",
    "print('Positive： {0}        {1}'.format(\n",
    "    len(training_predict_label_hog_positive[training_predict_label_hog_positive == 1]),len(training_predict_label_hog_positive[training_predict_label_hog_positive == 0])))\n",
    "print('Negative： {0}        {1}'.format(\n",
    "    len(training_predict_label_hog_negative[training_predict_label_hog_negative == 0]),len(training_predict_label_hog_negative[training_predict_label_hog_negative == 1])))\n",
    "print('检测率: {0}, 虚警率: {1}'.format(\n",
    "    (len(training_predict_label_hog_positive[training_predict_label_hog_positive == 1]) + 0.0) / len(training_predict_label_hog_positive),\n",
    "    (len(training_predict_label_hog_negative[training_predict_label_hog_negative == 1]) + 0.0) / len(training_predict_label_hog_negative)\n",
    "))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T14:28:10.481545Z",
     "start_time": "2018-05-07T14:28:10.100408Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "HOG+SVM Test Set Confusion Matrix\n",
      "          Ture      False\n",
      "Positive： 660        340\n",
      "Negative： 505        495\n",
      "检测率: 0.66, 虚警率: 0.495\n"
     ]
    }
   ],
   "source": [
    "print('HOG+SVM Test Set Confusion Matrix\\n          Ture      False')\n",
    "\n",
    "print('Positive： {0}        {1}'.format(\n",
    "    len(test_predict_label_hog_positive[test_predict_label_hog_positive == 1]),len(test_predict_label_hog_positive[test_predict_label_hog_positive == 0])))\n",
    "print('Negative： {0}        {1}'.format(\n",
    "    len(test_predict_label_hog_negative[test_predict_label_hog_negative == 0]),len(test_predict_label_hog_negative[test_predict_label_hog_negative == 1])))\n",
    "print('检测率: {0}, 虚警率: {1}'.format(\n",
    "    (len(test_predict_label_hog_positive[test_predict_label_hog_positive == 1]) + 0.0) / len(test_predict_label_hog_positive),\n",
    "    (len(test_predict_label_hog_negative[test_predict_label_hog_negative == 1]) + 0.0) / len(test_predict_label_hog_negative)\n",
    "))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 计算LBP特征向量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T11:34:23.833286Z",
     "start_time": "2018-05-07T11:34:23.798387Z"
    }
   },
   "outputs": [],
   "source": [
    "class LocalBinaryPatterns:\n",
    "\tdef __init__(self, numPoints, radius):\n",
    "\t\t# store the number of points and radius\n",
    "\t\tself.numPoints = numPoints\n",
    "\t\tself.radius = radius\n",
    " \n",
    "\tdef describe(self, image, eps=1e-7):\n",
    "\t\t# compute the Local Binary Pattern representation\n",
    "\t\t# of the image, and then use the LBP representation\n",
    "\t\t# to build the histogram of patterns\n",
    "\t\tlbp = ft.local_binary_pattern(image, self.numPoints,\n",
    "\t\t\tself.radius, method=\"uniform\")\n",
    "\t\t(hist, _) = np.histogram(lbp.ravel(),\n",
    "\t\t\tbins=np.arange(0, self.numPoints + 3),\n",
    "\t\t\trange=(0, self.numPoints + 2))\n",
    " \n",
    "\t\t# normalize the histogram\n",
    "\t\thist = hist.astype(\"float\")\n",
    "\t\thist /= (hist.sum() + eps)\n",
    " \n",
    "\t\t# return the histogram of Local Binary Patterns\n",
    "\t\treturn hist"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T11:34:37.308783Z",
     "start_time": "2018-05-07T11:34:37.306025Z"
    }
   },
   "outputs": [],
   "source": [
    "lbp_descriptor = LocalBinaryPatterns(16, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T11:36:40.187027Z",
     "start_time": "2018-05-07T11:34:50.947339Z"
    }
   },
   "outputs": [],
   "source": [
    "training_set_lbp = [lbp_descriptor.describe(cv2.resize(cv2.cvtColor(i, cv2.COLOR_BGR2GRAY), (256, 256))) for i in training_set]\n",
    "training_set_lbp_nparray = np.vstack(training_set_lbp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T11:37:32.749364Z",
     "start_time": "2018-05-07T11:37:05.458278Z"
    }
   },
   "outputs": [],
   "source": [
    "test_set_lbp = [lbp_descriptor.describe(cv2.resize(cv2.cvtColor(i, cv2.COLOR_BGR2GRAY), (256, 256))) for i in test_set]\n",
    "test_set_lbp_nparray = np.vstack(test_set_lbp)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 训练svm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T11:38:01.849218Z",
     "start_time": "2018-05-07T11:38:01.842082Z"
    }
   },
   "outputs": [],
   "source": [
    "clf_lbp = svm.SVC()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T11:38:30.191931Z",
     "start_time": "2018-05-07T11:38:30.095528Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,\n",
       "  decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf',\n",
       "  max_iter=-1, probability=False, random_state=None, shrinking=True,\n",
       "  tol=0.001, verbose=False)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "clf_lbp.fit(training_set_lbp_nparray, training_label)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T11:39:00.381651Z",
     "start_time": "2018-05-07T11:39:00.356918Z"
    }
   },
   "outputs": [],
   "source": [
    "test_predict_label_lbp = clf_lbp.predict(test_set_lbp_nparray)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T11:39:29.161503Z",
     "start_time": "2018-05-07T11:39:29.158060Z"
    }
   },
   "outputs": [],
   "source": [
    "test_predict_label_lbp_positive = test_predict_label_lbp[:100]\n",
    "test_predict_label_lbp_negative = test_predict_label_lbp[100:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T11:39:58.924392Z",
     "start_time": "2018-05-07T11:39:58.721034Z"
    }
   },
   "outputs": [],
   "source": [
    "training_predict_label_lbp = clf_lbp.predict(training_set_lbp_nparray)\n",
    "training_predict_label_lbp_positive = training_predict_label_lbp[:400]\n",
    "training_predict_label_lbp_negative = training_predict_label_lbp[400:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T11:40:55.733271Z",
     "start_time": "2018-05-07T11:40:55.719188Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LBP+SVM Training Set Confusion Matrix\n",
      "          Ture      False\n",
      "Positive： 171        229\n",
      "Negative： 329        71\n",
      "检测率: 0.4275, 虚警率: 0.1775\n"
     ]
    }
   ],
   "source": [
    "print('LBP+SVM Training Set Confusion Matrix\\n          Ture      False')\n",
    "\n",
    "print('Positive： {0}        {1}'.format(\n",
    "    len(training_predict_label_lbp_positive[training_predict_label_lbp_positive == 1]),len(training_predict_label_lbp_positive[training_predict_label_lbp_positive == 0])))\n",
    "print('Negative： {0}        {1}'.format(\n",
    "    len(training_predict_label_lbp_negative[training_predict_label_lbp_negative == 0]),len(training_predict_label_lbp_negative[training_predict_label_lbp_negative == 1])))\n",
    "print('检测率: {0}, 虚警率: {1}'.format(\n",
    "    (len(training_predict_label_lbp_positive[training_predict_label_lbp_positive == 1]) + 0.0) / len(training_predict_label_lbp_positive),\n",
    "    (len(training_predict_label_lbp_negative[training_predict_label_lbp_negative == 1]) + 0.0) / len(training_predict_label_lbp_negative)\n",
    "))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-05-07T11:40:27.452330Z",
     "start_time": "2018-05-07T11:40:27.439041Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LBP+SVM Test Set Confusion Matrix\n",
      "          Ture      False\n",
      "Positive： 53        47\n",
      "Negative： 78        22\n",
      "检测率: 0.53, 虚警率: 0.22\n"
     ]
    }
   ],
   "source": [
    "print('LBP+SVM Test Set Confusion Matrix\\n          Ture      False')\n",
    "\n",
    "print('Positive： {0}        {1}'.format(\n",
    "    len(test_predict_label_lbp_positive[test_predict_label_lbp_positive == 1]),len(test_predict_label_lbp_positive[test_predict_label_lbp_positive == 0])))\n",
    "print('Negative： {0}        {1}'.format(\n",
    "    len(test_predict_label_lbp_negative[test_predict_label_lbp_negative == 0]),len(test_predict_label_lbp_negative[test_predict_label_lbp_negative == 1])))\n",
    "print('检测率: {0}, 虚警率: {1}'.format(\n",
    "    (len(test_predict_label_lbp_positive[test_predict_label_lbp_positive == 1]) + 0.0) / len(test_predict_label_lbp_positive),\n",
    "    (len(test_predict_label_lbp_negative[test_predict_label_lbp_negative == 1]) + 0.0) / len(test_predict_label_lbp_negative)\n",
    "))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda root]",
   "language": "python",
   "name": "conda-root-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  },
  "toc": {
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": "block",
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
